package com.smilive.start.netty.jdk;

import com.google.common.collect.Lists;
import com.smilive.start.netty.utils.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;

/**
 * @program: netty_start
 * @Date: 2022-01-04 13:51
 * @Author: smilive
 * @Description:
 */
@Slf4j
public class NetServerBlocking {

    public static void main(String[] args) {

        //创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(16);
        //获取服务端通道
        try (ServerSocketChannel server = ServerSocketChannel.open()){
            //绑定端口
            server.bind(new InetSocketAddress(8000));
            //创建连接集合
            ArrayList<SocketChannel> channels = Lists.newArrayList();
            //循环接收连接
            while (true){
                log.debug("等待连接接入....");
                // 没有连接时，会阻塞线程
                SocketChannel socketChannel = server.accept();
                log.debug("连接接入:{}",socketChannel);
                channels.add(socketChannel);
                //循环遍历处理通道数据
                for (SocketChannel channel : channels) {
                    // 处理通道中的数据
                    // 当通道中没有数据可读时，会阻塞线程
                    log.debug("等待通道数据...");
                    channel.read(buffer);
                    buffer.flip();
                    ByteBufferUtil.debugAll(buffer);
                    buffer.clear();
                    log.debug("接收数据完毕");
                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
